package com.wzl.jdbc.config;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

/**
 * 精准分表算法
 *
 * @author wzl
 * @date 2024/05/12 11:01
 */
public class MyTablePreciseShardingAlgorithm implements PreciseShardingAlgorithm<Integer> {

    @Override
    public String doSharding(Collection<String> tableNames, PreciseShardingValue<Integer> shardingValue) {

        /**
         * databaseNames 所有分片库的集合
         * shardingValue 为分片属性，其中 logicTableName 为逻辑表，columnName 分片键，value 为从 SQL 中解析出的分片键的值
         */
        for (String tableName : tableNames) {
            // 根据编号判断，number % 3 取余数 对应t_user_X表
            String value = String.valueOf(shardingValue.getValue() % 3);
            if (tableName.endsWith(value)) {
                return tableName;
            }
        }
        throw new IllegalArgumentException("分片失败，tableNames：" + tableNames);
    }
}
